const joi = require('joi');
const dbQuery = require('../model/db');
const {
	sendError,
	sendSuccess
} = require('../utils/sendFunction');

// 验证规则
const schemaAddMv = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	singerId: joi.number().required().error(new Error('singerId不符合验证规则')),
})

const schemaDeleteMvAndGet = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaEditMv = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	singerId: joi.number().required().error(new Error('singerId不符合验证规则')),
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

// name mvurl mvfile picfile singerId
const addMv = async function (req, res, next) {
	let info = req.body;

	if (!info.name || !info.singerId) {
		sendError(res, 200, 'MV名称或歌手不能为空!');
		return;
	}

	if (!req.files["picfile"]) {
		sendError(res, 200, '图片不能为空！')
		return;
	}

	if (!info.mvurl && !req.files["mvfile"]) {
		sendError(res, 200, 'MV地址或MV文件不能为空！');
		return;
	}

	try {
		await schemaAddMv.validateAsync({
			name: info.name,
			singerId: info.singerId,
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from mv where mv_name=?';
	let result = await dbQuery(sqlStr, info.name);
	if (result.length !== 0) {
		sendError(res, 200, 'MV名称被占用，请更换其他MV名称!');
		return;
	}

	if (!info.mvurl) {
		var file = req.files["mvfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/')
	} else {
		var mvurl = info.mvurl;
	}

	var img = req.files["picfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
	let sqlStr1 = 'insert into mv (mv_name,mv_url,mv_file,mv_pic_url,singer_id) values (?,?,?,?,?)';
	let result1 = await dbQuery(sqlStr1, [info.name, mvurl, file, img, info.singerId]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '添加MV成功!');
	} else {
		sendError(res, 500, '添加MV失败，请稍后再试!')
	}
}

// id
const deleteMv = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaDeleteMvAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let result3 = await dbQuery('select * from mv where mvid=?',[id])
	if(result3.length==0){
		sendError(res, 200, '删除MV失败，该MV已被删除!')
		return;
	}

	// 级联删除
	let sqlStr = 'delete from mv where mvid=?'
	let result = await dbQuery(sqlStr, [id]);
	let sqlStr1 = 'delete from collect where mv_id=?';
	let result1 = await dbQuery(sqlStr1, [id]);
	let sqlStr2 = 'delete from comment where mv_id=?';
	let result2 = await dbQuery(sqlStr2, [id]);
	if (result.affectedRows == 1 && result2.affectedRows >= 0 && result1.affectedRows >= 0) {
		sendSuccess(res, '删除MV成功!');
	} else {
		sendError(res, 500, '删除MV失败，请稍后再试!')
	}
}

const getMv = async function (req, res, next) {
	let sqlStr = 'select mv.*,singer.* from mv inner join singer on mv.singer_id=singer.singerid';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取MV成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取MV失败，请稍后再试!')
	}
}

const getMvById = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空！');
		return;
	}

	try {
		await schemaDeleteMvAndGet.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select mv.*,singer.* from mv inner join singer on mv.singer_id=singer.singerid where mvid=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result.length >= 0) {
		sendSuccess(res, '获取MV成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取MV失败，请稍后再试!')
	}
}

const getMvBySingerId = async function (req, res, next) {
	let {
		singerid
	} = req.query;

	if (!singerid) {
		sendError(res, 200, '歌手不能为空！');
		return;
	}

	try {
		await schemaDeleteMvAndGet.validateAsync({
			id: singerid
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select mv.*,singer.* from mv inner join singer on mv.singer_id=singer.singerid where mv.singer_id=?';
	let result = await dbQuery(sqlStr, [singerid]);
	if (result.length >= 0) {
		sendSuccess(res, '获取MV成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取MV失败，请稍后再试!')
	}
}

// id name mvurl mvfile picfile singerId
const editMv = async function (req, res, next) {
	let info = req.body;

	if (!info.name || !info.singerId || !info.id) {
		sendError(res, 200, 'MV名称或歌手或id不能为空!');
		return;
	}

	try {
		await schemaEditMv.validateAsync({
			name: info.name,
			singerId: info.singerId,
			id: info.id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from mv where mv_name=? and mvid!=?';
	let result = await dbQuery(sqlStr, [info.name, info.id]);
	if (result.length !== 0) {
		sendError(res, 200, 'MV名称被占用，请更换其他MV名称!');
		return;
	}

	var sqlStr1;
	var result1;
	// mvurl mvfile picfile不一定要改
	if (req.files["picfile"]) {
		let img = req.files["picfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
		if (req.files["mvfile"] && !info.mvurl) {
			let file = req.files["mvfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
			sqlStr1 = 'update mv set mv_name=?,mv_file=?,mv_pic_url=?,singer_id=?,mv_url=null where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, file, img, info.singerId, info.id]);
		} else if (!req.files["mvfile"] && info.mvurl) {
			sqlStr1 = 'update mv set mv_name=?,mv_url=?,mv_pic_url=?,singer_id=?,mv_file=null where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.mvurl, img, info.singerId, info.id]);
		} else if (req.files["mvfile"] && info.mvurl) {
			sqlStr1 = 'update mv set mv_name=?,mv_url=?,mv_pic_url=?,singer_id=?,mv_file=null where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.mvurl, img, info.singerId, info.id]);
		} else if (!req.files["mvfile"] && !info.mvurl) {
			sqlStr1 = 'update mv set mv_name=?,mv_pic_url=?,singer_id=? where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, img, info.singerId, info.id]);
		}
		if (result1.affectedRows == 1) {
			sendSuccess(res, '修改MV成功!');
		} else {
			sendError(res, 500, '修改MV失败，请稍后再试!')
		}
	} else {
		if (req.files["mvfile"] && !info.mvurl) {
			let file = req.files["mvfile"][0].path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
			sqlStr1 = 'update mv set mv_name=?,mv_file=?,singer_id=?,mv_url=null where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, file, info.singerId, info.id]);
		} else if (!req.files["mvfile"] && info.mvurl) {
			sqlStr1 = 'update mv set mv_name=?,mv_url=?,singer_id=?,mv_file=null where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.mvurl, info.singerId, info.id]);
		} else if (req.files["mvfile"] && info.mvurl) {
			sqlStr1 = 'update mv set mv_name=?,mv_url=?,singer_id=?,mv_file=null where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.mvurl, info.singerId, info.id]);
		} else if (!req.files["mvfile"] && !info.mvurl) {
			sqlStr1 = 'update mv set mv_name=?,singer_id=? where mvid=?';
			result1 = await dbQuery(sqlStr1, [info.name, info.singerId, info.id]);
		}
		if (result1.affectedRows == 1) {
			sendSuccess(res, '修改MV成功!');
		} else {
			sendError(res, 500, '修改MV失败，请稍后再试!')
		}
	}
}


module.exports = {
	addMv,
	deleteMv,
	getMv,
	editMv,
	getMvById,
	getMvBySingerId
}